#!/bin/bash
#set -x
set -euo pipefail

cd `dirname ${BASH_SOURCE[0]}`
SHELL_FOLDER=$(pwd)
DEPLOY_ROOT=$(pwd)

source $DEPLOY_ROOT/utils/log.sh
source $DEPLOY_ROOT/utils/status.sh
source $DEPLOY_ROOT/init/base.sh  

INFO "Set install state to status.json"
status=$(cat $DEPLOY_ROOT/status.json)
state=$(echo $status | jq -r --exit-status '.state')
if [[ $state = "finish" ]]; then
    WARN "Installation has been finished, will not install again."
    exit 0
else
    INFO "Current deploy state: $state"
    state_set "install"
fi

# 过滤空行和以'#'开头的注释行
components=$(cat $DEPLOY_ROOT/modules.list | grep -v '^\s*$' | grep -v '^#')
for component in $components; do 
    component=$(echo $component | xargs)
    recover=$(recover_get)
    # 判断当前status.json中定义的module是否在modules.list中
    module=$(module_get)
    set +e
    if [ -n "$module" ]; then
      install_state=$(cat $DEPLOY_ROOT/modules.list | grep -v '^\s*$' | grep -v '^#' | grep $module)
    fi
    set -e

    if [ -n "$module" ] && [ -z "$install_state" ]; then
      ERROR "Current module $module defined in status.json not in modules.list exit..."
      ERROR "修正status.json文件中定义的module为modules.list中下一个需要部署的组件"
      exit 1
    fi

    if [[ $recover == "yes" && $component != $module ]]; then
        WARN "[$component] already installed, skip."
        continue
    else
        module_set $component
        recover_set "yes"
        INFO "Install: [$component]"
        cd $DEPLOY_ROOT/modules/${component}
        INFO "Work dir: $(pwd)"
        ansible-playbook deploy.yaml --skip-tags='download'
        recover_set "no"
    fi
done
state_set "finish"

INFO "Post do after all components deployed."
bash $DEPLOY_ROOT/utils/unable_configure.sh
bash $DEPLOY_ROOT/utils/cleanup.sh

NOTICE "Congratulations! Deploy all modules Done"
